package liaotian;

import Interface.User.User;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client extends Application {

    private PrintWriter out;
    private BufferedReader in;
    private TextField inputField;
    private TextArea messageArea;
    public static String nickname;

    @Override
    public void start(Stage primaryStage) {
        inputField = new TextField();
        inputField.setOnAction(e -> sendMessage(inputField.getText()));

        messageArea = new TextArea();
        messageArea.setEditable(false);

        VBox vbox = new VBox();
        vbox.getChildren().addAll(messageArea, inputField);

        Scene scene = new Scene(vbox, 400, 300);
        primaryStage.setScene(scene);
        primaryStage.setTitle("会员交流");
        primaryStage.show();

        System.out.println(nickname);

        try {
            Socket socket = new Socket("localhost", 7777);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            Thread receiveThread = new Thread(() -> {
                try {
                    String message;
                    while ((message = in.readLine()) != null) {
                        messageArea.appendText(message + "\n");
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            });
            receiveThread.start();

            // 发送昵称信息给服务器
            out.println(nickname);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendMessage(String message) {
        if (!message.isEmpty()) {
            out.println(message);
            inputField.clear();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
